import Vue from "vue"
import Vuex from "vuex"
import {getRequest} from "@/utils/requestUtil";
import api from "@/api";
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import {Notification} from "element-ui";
import router from "@/router";

Vue.use(Vuex);

const now = new Date();

const store = new Vuex.Store({
    //数据存储的地方
    state: {
        routers: [],
        sessions: {},
        admins: [],
        currentSession: {},
        currentAdmin: {},
        filterKey: '',
        stomp: null,
        subscribe:null
    },
    //同步的修改
    mutations: {
        initRouters(state, data) {
            state.routers = data
        },
        initCurrentAdmin(state,data) {
            state.currentAdmin=data
        },
        resetState(state) {
            state={
                routers: [],
                sessions: {},
                admins: [],
                currentSession: {},
                currentAdmin: {},
                filterKey: '',
                stomp: null
            }
        },
        changeCurrentSession(state, currentSession) {
            currentSession.unread=0
            state.currentSession = currentSession;
        },
        addMessage(state, msg) {
            let key = state.currentAdmin.username + '#' + msg.to
            if (!state.sessions[key]) {
                Vue.set(state.sessions, state.currentAdmin.username + '#' + msg.to, [])
            }
            if (msg.from && router.currentRoute.path==='/chat' && state.currentSession.username !== msg.from) {
                state.admins[state.admins.findIndex(item => item.username === msg.from)].unread += 1
                Notification({
                    title: `您有一条来自【${msg.fromNickName}】的消息`,
                    message: msg.content.substring(0, 10) + '……',
                    type: 'info'
                })
            }
            state.sessions[key].push({
                content: msg,
                date: new Date(),
                self: !msg.from
            })
        },
        INIT_DATA(state) {
            let data = localStorage.getItem('vue-chat-session-'+store.state.currentAdmin.username);
            if (data) {
                state.sessions = JSON.parse(data);
            }
        },
        INIT_ADMINS(state, data) {
            if (state.admins.length <= 0) {
                for (let obj of data) {
                    obj.unread = 0
                }
                state.admins = data
            }
        }
    },
    //异步的修改
    actions: {
        //websocket的连接
        connect(context) {
            let {state} = context;
            state.stomp = Stomp.over(new SockJS('/ws/ep'))
            state.stomp.debug=()=>{}//关闭stomp的控制台输出
            state.stomp.connect(
                {'Auth-Token': sessionStorage.getItem('token_login')},
                success => {
                    state.subscribe = state.stomp.subscribe('/user/queue/chat', msg => {
                        let parse = JSON.parse(msg.body);
                        console.log(parse)
                        parse.to = parse.from
                        context.commit('addMessage', parse)
                    })
                },
                error => {
                    console.log(error)
                }
            )
        },
        initData(context) {
            getRequest(api.chatAdmin).then(res => {
                if (res) {
                    context.commit('INIT_ADMINS', res.data)
                    context.commit('INIT_DATA')
                }
            })
        }
    }
})

store.watch(function (state) {
    return state.sessions
}, function (val) {
    localStorage.setItem('vue-chat-session-'+store.state.currentAdmin.username, JSON.stringify(val));
}, {
    deep: true
})

store.watch(function (state) {
    return state.admins
}, function (val) {
    localStorage.setItem('vue-chat-admins', JSON.stringify(val));
}, {
    deep: true
})

export default store;